from sqlalchemy import select, insert
from domain.models.models import ActivityChat
from db.db import async_session
from common.tencent_im import TencentIM

async def create_chatroom(activity_id: int, creator_id: str, member_list: list, group_name: str = None, notification: str = None) -> tuple[bool, str]:
    """
    创建聊天室并保存到数据库
    """
    im = TencentIM()
    
    try:
        # 使用传入的群名称和公告，如果没有则使用默认值
        chat_name = group_name or f"活动群-{activity_id}"
        chat_notification = notification or "欢迎加入活动群！"
        
        success, group_id = await im.create_group(
            group_name=chat_name,
            introduction=f"活动{activity_id}的聊天群组",
            notification=chat_notification,
            member_list=member_list,
            owner_id=creator_id
        )
        
        if not success:
            return False, f"创建群组失败: {group_id}"
            
        # 将群组信息保存到数据库
        async with async_session() as session:
            new_chatroom = ActivityChat(
                chat_id=group_id,
                activity_id=activity_id,
                name=chat_name,
                is_delete=0
            )
            
            session.add(new_chatroom)
            await session.commit()
            
            return True, group_id
            
    except Exception as e:
        return False, str(e)

async def get_chatroom_by_activity(activity_id: int) -> tuple[bool, dict]:
    """
    根据活动ID获取聊天室信息
    """
    async with async_session() as session:
        result = await session.execute(
            select(ActivityChat).where(
                ActivityChat.activity_id == activity_id,
                ActivityChat.is_delete == 0
            )
        )
        chatroom = result.scalar_one_or_none()
        
        if chatroom:
            return True, {
                "id": chatroom.id,
                "group_id": chatroom.chat_id,
                "activity_id": chatroom.activity_id,
                "name": chatroom.name
            }
        return False, None

async def get_chatroom_by_id(chatroom_id: int) -> tuple[bool, dict]:
    """
    根据聊天室ID获取聊天室信息
    """
    async with async_session() as session:
        result = await session.execute(
            select(ActivityChat).where(
                ActivityChat.id == chatroom_id,
                ActivityChat.is_delete == 0
            )
        )
        chatroom = result.scalar_one_or_none()
        
        if chatroom:
            return True, {
                "id": chatroom.id,
                "group_id": chatroom.group_id,
                "activity_id": chatroom.activity_id,
                "creator_id": chatroom.creator_id,
                "name": chatroom.name
            }
        return False, None

async def delete_chatroom(chatroom_id: int) -> tuple[bool, str]:
    """
    删除聊天室
    """
    im = TencentIM()

    async with async_session() as session:
        try:
            # 查询聊天室信息
            result = await session.execute(
                select(ActivityChat).where(
                    ActivityChat.id == chatroom_id,
                    ActivityChat.is_delete == 0
                )
            )
            chatroom = result.scalar_one_or_none()
            
            if not chatroom:
                return False, "聊天室不存在"
            
            # 删除腾讯云群组
            success, error = await im.delete_group(chatroom.chat_id)
            if not success:
                return False, f"删除群组失败: {error}"
            
            # 更新数据库记录
            chatroom.is_delete = 1
            await session.commit()
            
            return True, "删除成功"
            
        except Exception as e:
            await session.rollback()
            return False, str(e)